using System;
using CommonDomain.Persistence;

namespace Sponsorship.Domain.SponsorshipTypes
{
    /// <summary>
    /// Handles domain commands dealing with <see cref="SponsorshipType"/> instances.
    /// </summary>
    public class SponsorshipTypeCommandHandler :
        ICommandHandler<EnterSponsorshipType>,
        ICommandHandler<ChangeSponsorshipType>,
        ICommandHandler<DeleteSponsorshipType>
    {
        private readonly IRepository _repository;

        public SponsorshipTypeCommandHandler (IRepository repository)
        {
            _repository = repository;
        }

        public void Handle (EnterSponsorshipType command)
        {
            var sponsorshipType = new SponsorshipType (command.SponsorshipTypeId, command.Name, command.Amount, command.Period, command.Comment);

            //save new raised events of aggregate into eventstore
            SaveSponsorshipType (sponsorshipType);
        }

        public void Handle (ChangeSponsorshipType command)
        {
            SponsorshipType sponsorshipType = LoadSponsorshipType (command.SponsorshipTypeId, command.Version);

            //execute domain logic and get back a new aggregate
            sponsorshipType.Delete();

            //save new raised events of aggregate into eventstore
            SaveSponsorshipType (sponsorshipType);
        }

        public void Handle (DeleteSponsorshipType command)
        {
            SponsorshipType sponsorshipType = LoadSponsorshipType (command.SponsorshipTypeId, command.Version);

            //execute domain logic and get back a new aggregate
            sponsorshipType.Delete();

            //save new raised events of aggregate into eventstore
            SaveSponsorshipType (sponsorshipType);
        }

        //private SponsorshipType LoadSponsorshipType(Guid guid)
        //{
        //    return _repository.GetById<SponsorshipType>(guid);
        //}

        private SponsorshipType LoadSponsorshipType (Guid guid, int version)
        {
            return _repository.GetById<SponsorshipType> (guid, version);
        }

        private void SaveSponsorshipType (SponsorshipType sponsorship)
        {
            _repository.Save (sponsorship, Guid.NewGuid()); // Every commit has a new ID
        }
    }
}